// ignore_for_file: file_names, must_be_immutable, constant_identifier_names, slash_for_doc_comments, avoid_unnecessary_containers, prefer_const_constructors, unnecessary_cast, sized_box_for_whitespace, prefer_function_declarations_over_variables, overridden_fields, annotate_overrides, prefer_const_literals_to_create_immutables, unnecessary_null_comparison, deprecated_member_use, invalid_use_of_protected_member, unused_element, unused_local_variable, avoid_print

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mybase/base/abstract/IFFRefresh.dart';
import 'package:mybase/base/abstract/IFFScaffold.dart';
import 'package:mybase/base/config/FFireBaseManager.dart';
import 'package:mybase/base/config/YCGlobalManger.dart';
import 'package:mybase/base/tool/Animated/AnimatedSkeleton.dart';
import 'package:mybase/base/tool/arouter/FFGoto.dart';
import 'package:mybase/base/tool/color/FFColor.dart';
import 'package:mybase/base/tool/empty/FFEmpty.dart';
import 'package:mybase/base/tool/eventBus/eventBus.dart';
import 'package:mybase/base/tool/globalMethod/FFScreenValue.dart';
import 'package:mybase/base/tool/platformUtils/FFPlatform.dart';
import 'package:mybase/base/tool/pprint/FFLog.dart';
import 'package:mybase/base/tool/time/FFTime.dart';
import 'package:mybase/base/widget/busConst/BusConst.dart';
import 'package:mybase/base/widget/layout/FFMoreBrach.dart';

/**页面父类，所有的页面都应该继承此类 */
class FFScaffold extends StatefulWidget {
  String? ffName;

  FFScaffold({Key? key, this.ffName}) : super(key: key);

  @override
  State<FFScaffold> createState() => FFScaffoldState();
}

class FFScaffoldState extends State<FFScaffold>
    with
        RouteAware,
        // SingleTickerProviderStateMixin, //单个AnimationController
        TickerProviderStateMixin, //有多个AnimationController
        AutomaticKeepAliveClientMixin,
        WidgetsBindingObserver {
  List<dynamic> datas = [];

  /**页面基础控制 */
  late IFFScaffold iffScaffold;

  /**刷新控制 */
  IFFRefresh? iffRefresh;

  /**这次的状态与上次的状态是否改变了 */
  bool _statusChanged = false;

  /**上一次的状态 */
  FFPageStatus _lastPageStatus = FFPageStatus.firstLoading;

  /**
   * 键盘弹起时，是否resize
   */
  bool ffResizeToAvoidBottomInset = false;

  /**
   * 是否有背景层
   */
  bool ffHasBgWidget = false;

  /**
   * 是否有背景层2,介于背景层与内容层之间
   */
  bool ffHasBgWidget2 = false;

  /**
   * 是否有悬浮层
   */
  bool ffHasFloatWidget = false;

  /**
   * 是否有顶部悬浮
   */
  bool ffHasNaviFloat = false;

  /**
   * 是否有右下角悬浮
   */
  bool ffHasRightBottomFloat = false;

  /**
   * 是否有底部悬浮
   */
  bool ffHasBottomFloat = false;

  /**
   * 是否有底部悬浮
   */
  bool ffHasBottomFloat2 = false;

  /**
   * 是否有顶部悬浮层
   */
  bool ffHasTopFloatWidget = false;

  /**
   * 是否body能响应到点击
   */
  bool ffOnBodyClick = true;

  /**
   * 底部留出安全区域
   */
  bool ffBottomSafeSpacing = false;

  /**
   * 进入该页面时打印页面名字及销毁时提示
   */
  bool ffPrintInitDispose = true;

  /**
   * 是否有Scaffold
   */
  bool hasScaffold = true;

  /**
   * 在使用WillPopScope的功能时，ffLeftSideScrollPop=true也可以侧滑返回
   * 如果当前页面是tabbar的子页面，应设为false【会影响到tabbar的左右滚动】
   */
  bool ffLeftSideScrollPop = false;

  /**
   * 当前页面在最顶层
   */
  bool ffCurrentAtFirst = true;

  /**
   * 强制 屏幕宽度，如果不设置可能会导致setstate时，页面会回到顶部
   */
  bool ffScreenWidth = true;

  @override
  void initState() {
    /**子类初始化方法 */
    WidgetsBinding.instance.addObserver(this);
    if (ffPrintInitDispose) _printPageName();
    iffScaffold.ffInitState();
    ffInitStateAfterLoadData();
    FFireBaseManager().goPageBefore(widget.toString());

    if (YCGlobalManger().delegate != null) {
      // 语言更改
      bus.on<void>(BusConst.onLanguageChange, _onLangugeChange);
      BuildContext? buildContext = YCGlobalManger().delegate!.getBuildContext();
      if (buildContext != null) {
        ffOnLanguageChange(buildContext);
      }
    }

    super.initState();
  }

  // 语言更改
  _onLangugeChange(value) {
    if (!mounted) return;
    ffOnLanguageChange(context);
  }

  /**初始化页面 或者 语言更改，子类在这儿更新相关变量*/
  ffOnLanguageChange(BuildContext context) {}

  /**第一次加载，拿到数据setstate后执行*/
  ffirstAfterSetState() {}

  /**非第一次，并且是头刷新*/
  ffIsNotFirstAndHeadRefresh() {}

  /**找印页面名字，方便查找*/
  _printPageName() {
    String? pageInfo = ffPageInfo();
    if (!FFEmpty.stringIsEmpty(pageInfo)) {
      debugPrint("""
    
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
         进入到页面：class ${widget.toString()}
         该页面说明：
            ${pageInfo ?? "----"}
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    """);
    } else {
      debugPrint("""
    
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
         进入到页面：class ${widget.toString()}
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    """);
    }
  }

  /**用来说明该页面作用*/
  String? ffPageInfo() {
    return null;
  }

  void ffInitStateAfterLoadData() {
    if (iffRefresh != null) {
      iffRefresh!.ffFirstRefresh = true;
      iffRefresh!.ffRefresh(true);
    }
  }

  /**每个页面都可以自定义主题*/
  Widget ffBuildTheme(BuildContext context, {required Widget child}) {
    return child;
    // return Theme(
    //     data: ThemeData(
    //       primarySwatch: FFColor.createMaterialColor(
    //           Color.fromRGBO(56, 204, 96, 1.0).withAlpha(100)),
    //     ),
    //     child: child);
  }

  /**多语言渲染*/
  ffLanguageBuild(BuildContext context) {}

  /**刷新父类,子类使用自己的setState也是一样的*/
  ffSuperSetState() {
    setState(() {});
  }

  bool isAndroidAndIOS() {
    return (Platform.isAndroid || Platform.isIOS) ? true : false;
  }

  /**
   * @title 状态栏文字 图标颜色
   * @info  一般不重写这个方法，默认走iffScaffold.ffStyle?.ffStatusTextColor
   */
  SystemUiOverlayStyle? ffGetStatusTextColor(BuildContext context) {}

  @override
  Widget build(BuildContext context) {
    ffLanguageBuild(context);
    if (wantKeepAlive == true) super.build(context);
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: ffGetStatusTextColor(context) ??
          SystemUiOverlayStyle(
            // 顶部背景颜色
            statusBarColor: Colors.transparent,
            // 状态栏 亮色 暗色
            systemNavigationBarIconBrightness: (iffScaffold.ffStyle?.ffStatusTextColor == SystemUiOverlayStyle.light)
                ? Brightness.light
                : Brightness.dark,
            statusBarIconBrightness: (iffScaffold.ffStyle?.ffStatusTextColor == SystemUiOverlayStyle.light)
                ? Brightness.light
                : Brightness.dark,
            statusBarBrightness: (iffScaffold.ffStyle?.ffStatusTextColor == SystemUiOverlayStyle.light)
                ? Brightness.dark
                : Brightness.light,
            // 底部安全区域背景颜色
            systemNavigationBarColor: iffScaffold.ffStyle?.ffBodyColor ?? Colors.transparent,
            // 底部安全区域分隔线颜色
            systemNavigationBarDividerColor: Colors.transparent,
          ),
      child: MediaQuery.removePadding(
        context: context,
        removeTop: iffScaffold.ffTabbarRemoveTop ?? false,
        child: ffBuildTheme(context, child: _scaffold(context)),
      ),
    );
  }

  // @override
  // Widget build(BuildContext context) {
  //   ffLanguageBuild(context);
  //   if (wantKeepAlive == true) super.build(context);
  //   return MediaQuery.removePadding(
  //     context: context,
  //     removeTop: iffScaffold.ffTabbarRemoveTop ?? false,
  //     child: ffBuildTheme(context, child: _scaffold(context)),
  //   );
  // }

  Widget _scaffold(BuildContext context) {
    Widget? scaffold;
    if (hasScaffold) {
      scaffold = Scaffold(
        resizeToAvoidBottomInset: ffResizeToAvoidBottomInset,
        floatingActionButton: iffScaffold.ffloatingActionButton(context),
        backgroundColor: iffScaffold.ffStyle?.ffStatusBackgroundColor,
        bottomNavigationBar: iffScaffold.ffBottomNavigationBar(context),
        // ClipRect
        body: ClipRect(
          //不会超过一屏
          child: Stack(
            children: [
              Container(),
              // 最里面的背景层
              if (ffHasBgWidget == true) ffBgWidget(context) ?? Container(),
              // 里面的背景层
              if (ffHasBgWidget2 == true) ffBgWidget2(context) ?? Container(),
              // 内容层 (ffBodyColor会遮盖后面的背景层)
              mainColumn(),
              // 悬浮1层
              if (ffHasFloatWidget == true) ffloatWidget(context) ?? Container(),

              // 右下角悬浮
              if (ffHasRightBottomFloat == true)
                Positioned(
                  bottom: 0,
                  right: 0,
                  child: ffRightBottomFloat(context) ?? Container(),
                ),

              // 顶部悬浮
              if (ffHasNaviFloat == true)
                Positioned(
                  left: 0,
                  top: 0,
                  right: 0,
                  child: ffNaviFloat(context) ?? Container(),
                ),
              // 底部悬浮
              if (ffHasBottomFloat == true)
                Positioned(
                  left: 0,
                  right: 0,
                  bottom: 0,
                  child: ffBottomFloat(context) ?? Container(),
                ),

              // 底部悬浮
              if (ffHasBottomFloat2 == true)
                Positioned(
                  left: 0,
                  right: 0,
                  bottom: 0,
                  child: ffBottomFloat2(context) ?? Container(),
                ),

              // 最上面的悬浮层
              if (ffHasTopFloatWidget == true) ffTopFloatWidget(context) ?? Container(),
            ],
          ),
        ),
      );
    } else {
      scaffold = mainColumn();
    }

    /// 整个背景
    // Widget? bg = ffScaffoldBg(context);
    // if (bg != null) {
    //   scaffold = Stack(
    //     children: [
    //       Positioned.fill(child: bg),
    //       scaffold,
    //     ],
    //   );
    // }

    late Widget child;
    // 在使用WillPopScope的功能时，ffLeftSideScrollPop=true也可以侧滑返回
    if (ffLeftSideScrollPop) {
      child = Platform.isIOS
          // ? GestureDetector(
          //     onHorizontalDragUpdate: (details) async {
          //       if (details.delta.dx >= 0 && details.localPosition.dx < 50) {
          //         bool can = await ffOnWillPop();
          //         if (can) {
          //           if (context.mounted) {
          //             FFGoto.pop(context);
          //           }
          //         }
          //       }
          //     },
          //     child: WillPopScope(
          //       onWillPop: ffOnWillPop,
          //       child: scaffold,
          //     ),
          //   )
          ? PopScope(
              canPop: ffLeftSideScrollPop,
              child: scaffold,
            )
          : WillPopScope(
              onWillPop: ffOnWillPop,
              child: scaffold,
            );
    } else {
      child = WillPopScope(
        onWillPop: ffOnWillPop,
        child: scaffold,
      );
    }

    if (ffOnBodyClick) {
      return GestureDetector(
        onTap: () {
          // 收起键盘
          ffBodyGestureDetector();
        },
        child: child,
      );
    } else {
      return child;
    }
  }

  ffBodyGestureDetector() {
    FocusScope.of(context).requestFocus(FocusNode());
    ffOnScaffoldTap();
  }

  Column mainColumn() {
    return Column(
      children: [
        ///导航栏
        //MediaQuery.removePadding 很重要
        MediaQuery.removePadding(
          context: context,
          removeBottom: true,
          child: iffScaffold.ffNavi(context) ?? Container(),
        ),

        ///导航栏 底部固定区域
        iffScaffold.ffNaviBottomFixedArea(context) ?? Container(),

        Expanded(
          child: FFMoreBrach(
            condition: iffScaffold.ffPageStatus,
            builderWidget: (BuildContext ctx, dynamic condition) {
              //状态过渡有动画
              Widget? thisWidget;
              if (condition is FFPageStatus) {
                if (_lastPageStatus != condition) {
                  _statusChanged = !_statusChanged;
                }

                if (condition == FFPageStatus.firstLoading) {
                  thisWidget = iffScaffold.ffFirstLoadingWidget(context);
                } else if (condition == FFPageStatus.noData) {
                  thisWidget = _refreshWidget(
                      context,
                      iffScaffold.ffNoDataWidget(context, obj: FFEventObj(firstRefresh: () {
                            ffRequestFirstRefresh();
                          })) ??
                          Container(),
                      condition);
                } else if (condition == FFPageStatus.netError) {
                  thisWidget = _refreshWidget(
                      context,
                      iffScaffold.ffNetErrorWidget(context, obj: FFEventObj(firstRefresh: () {
                            ffRequestFirstRefresh();
                          })) ??
                          Container(),
                      condition);
                } else if (condition == FFPageStatus.result) {
                  thisWidget = _refreshWidget(context, iffScaffold.ffBody(context) ?? Container(), condition);
                }

                _lastPageStatus = condition;
              }

              return Container(
                width: ffScreenWidth ? MediaQuery.of(context).size.width : null, // 宽度
                color: iffScaffold.ffStyle?.ffBodyColor,
                child: AnimatedSkeleton(
                  isLoading: _statusChanged,
                  skeletonWidget: thisWidget ?? Container(),
                  body: Container(
                    child: thisWidget,
                  ),
                ),
              );
            },
          ),
        ),

        ///底部固定
        iffScaffold.ffBottom(context) ?? Container(),
        Container(
          padding: iffScaffold.ffPageSpacingParam?.bottomSpacing == true
              ? EdgeInsets.only(bottom: MediaQuery.of(context).padding.bottom * 0.55)
              : null,
        ),
        if (ffBottomSafeSpacing && FFPlatform.isIOS)
          Container(
            margin: EdgeInsets.only(bottom: globalScreenPaddingTop(context) * 0.5),
          ),
      ],
    );
  }

  ///点击空白的地方
  ffOnScaffoldTap() {}

  ///背景层:ffHasBgWidget=true才有效
  Widget? ffBgWidget(BuildContext context) {
    return null;
  }

  ///背景层与内容层之间的层:ffHasBgWidget2=true才有效
  Widget? ffBgWidget2(BuildContext context) {
    return null;
  }

  ///悬浮层,ffHasFloatWidget=true才有效
  Widget? ffloatWidget(BuildContext context) {
    return null;
  }

  ///顶部悬浮,ffHasNaviFloat=true才有效
  Widget? ffNaviFloat(BuildContext context) {
    return null;
  }

  ///右下角悬浮,ffHasRightBottomFloat=true才有效
  Widget? ffRightBottomFloat(BuildContext context) {
    return null;
  }

  ///底部悬浮,ffHasBottomFloat=true才有效
  Widget? ffBottomFloat(BuildContext context) {
    return null;
  }

  ///底部悬浮,ffHasBottomFloat=true才有效
  Widget? ffBottomFloat2(BuildContext context) {
    return null;
  }

  ///top悬浮,ffHasTopFloatWidget=true才有效
  Widget? ffTopFloatWidget(BuildContext context) {
    return null;
  }

  ///重新进入第一次刷新
  ///isForce=true,将忽略之前的刷新
  void ffRequestFirstRefresh({
    bool isForce = false,
  }) {
    iffScaffold.ffPageStatus = FFPageStatus.firstLoading;
    setState(() {});
    ffRequestBackRefresh(isForce: isForce);
  }

  ///后台偷偷刷新，正常情况下不显示加载效果
  void ffRequestBackRefresh({
    bool isForce = false,
  }) {
    if (!mounted) return;
    if (isForce == true) {
      // 这是强制刷新的
      iffRefresh?.refreshCode = FFTime.nowMillSecond().toString();
      iffScaffold.ffPageStatus = FFPageStatus.firstLoading;
      setState(() {});
      iffRefresh?.ffRefresh(true);

      return;
    }

    if (iffRefresh?.ffrefreshApiStatus != RefreshApiStatus.status_none) {
      debugPrint("正在刷新，忽略");
      return;
    }
    if (iffScaffold.ffPageStatus == FFPageStatus.noData || iffScaffold.ffPageStatus == FFPageStatus.netError) {
      iffScaffold.ffPageStatus = FFPageStatus.firstLoading;
      setState(() {});
    }
    iffRefresh?.ffRefresh(true);
  }

  ///能否侧滑返回
  Future<bool> ffOnWillPop() {
    return Future(() => true);
  }

  ///键盘高度变化
  ffKeyBoardChange(EdgeInsets insets) {}

  @override
  void didChangeMetrics() {
    if (!mounted) return;
    super.didChangeMetrics();

    // MediaQueryData? data = MediaQuery.of(context);
    // if (data != null && data.viewInsets != null) {
    //   ffKeyBoardChange(data.viewInsets);
    // }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (ModalRoute.of(context) is PageRoute) {
      routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute);
    }
    FFireBaseManager().getGlobal()?.ffDidChangeDependencies(this, context);
    iffScaffold.ffDidChangeDependencies();

    MediaQueryData? data = MediaQuery.of(context);
    if (data != null && data.viewInsets != null) {
      ffKeyBoardChange(data.viewInsets);
    }
  }

  /**页面销毁执行些方法 */
  @override
  void dispose() {
    if (ffPrintInitDispose) debugPrint("页面销毁...");
    bus.off(BusConst.onLanguageChange, _onLangugeChange);
    routeObserver.unsubscribe(this);
    iffScaffold.ffDispose();
    WidgetsBinding.instance.removeObserver(this);
    FFireBaseManager().getGlobal()?.ffRemoveObserver(this);
    super.dispose();
  }

  /**push到当前页面 */
  @override
  void didPush() {
    super.didPush();
  }

  /**这个页面回到上个页面 */
  @override
  void didPop() {
    super.didPop();
  }

  /**当前页面push到下一页面 */
  @override
  void didPushNext() {
    super.didPushNext();
    ffCurrentAtFirst = false;
  }

  /**回到这个页面 */
  @override
  void didPopNext() {
    super.didPopNext();
    ffCurrentAtFirst = true;
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (!mounted) return;
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) {
      appEnterForeground();
    } else if (state == AppLifecycleState.paused) {
      appEnterBackground();
    }
  }

  /**app进入前台*/
  void appEnterForeground() {}

  /**app进入后台*/
  void appEnterBackground() {}

  /**在tabbar切换过程中，当前页面是否保存*/
  @override
  bool get wantKeepAlive => false;
}

/**刷新管理 */
extension RefreshManager on FFScaffoldState {
  Widget _refreshWidget(BuildContext ctx, Widget child, FFPageStatus status) {
    if (iffRefresh != null) {
      return iffRefresh!.ffWidget(ctx, child, status);
    }
    return child;
  }
}
